package com.xxl.job.admin.core.conf;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * @className: DetailedShardingJobHandler demo案例
 * @description: TODO
 * @author: yuanjun.xu
 * @date: 2025-04-24 09:42
 */
@Component
public class DetailedShardingJobHandler {
    private static final Logger logger = LoggerFactory.getLogger(DetailedShardingJobHandler.class);
    @XxlJob("detailedShardingJob")
    public ReturnT<String> execute(String param) throws Exception {
        int shardIndex = XxlJobHelper.getShardIndex();
        int shardTotal = XxlJobHelper.getShardTotal();
        logger.info("开始处理分片任务: shardIndex={}, shardTotal={}", shardIndex, shardTotal);
        try {
            String[] data = fetchData(shardTotal, shardIndex);
            for (String item : data) {
                processItem(item);
            }
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            logger.error("处理分片任务失败", e);
            return new ReturnT<>(ReturnT.FAIL_CODE, e.getMessage());
        }
    }
    private String[] fetchData(int shardTotal, int shardIndex) {
        // 实现从数据库或其他数据源根据分片索引获取数据的逻辑
        return new String[]{"item" + shardIndex};
    }
    private void processItem(String item) {
        logger.info("处理项目: {}", item);
    }
}
